package com.example.mq.demotopic;

import com.example.mq.mqclient.Channel;
import com.example.mq.mqclient.Connection;
import com.example.mq.mqclient.ConnectionFactory;
import com.example.mq.mqserver.core.BasicProperties;

import java.io.IOException;

/**
 * 用此类来表示一个消费者
 * 也可以看作是一个单独的服务器
 */
public class Consumer2 {
    public static void main(String[] args) throws IOException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(9090);

        Connection connection = connectionFactory.getNewConnection();
        Channel channel = connection.createChannel();
        channel.basicConsumer("queue2", false, new com.example.mq.common.Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) {
                System.out.println("[消费数据开始]");
                System.out.println("consumerTag: " + consumerTag);
                String message = new String(body,0,body.length);
                System.out.println("message: " + message);
                System.out.println("routingKey: " + basicProperties.getRoutingKey());
                System.out.println("[消费数据结束]");
                try {
                   channel.basicAck("queue2",basicProperties.getMessageId());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
        //由于不知道有多少生产者，所以使用一个循环等待
        while (true) {
            Thread.sleep(500);
        }
    }

}


